import { useNavigate } from 'react-router-dom'
import React, { useEffect } from 'react'
import {
  Button,
  Space,
  InputNumber,
  Drawer,
  Checkbox,
  message,
  Empty,
  Typography,
  Input
} from 'antd'
import useState from 'react-usestateref'
import { CloseOutlined, ShoppingCartOutlined } from '@ant-design/icons'
import { $api } from '@/http/api'
const Cart = () => {
  const navigate = useNavigate()
  const [isModalVisible, setIsModalVisible, ref] = useState(false)
  const [cartList, setCartList] = useState([])
  const [phoneNumber, setPhoneNumber] = useState('')
  const [address, setAddress] = useState('')

  const getCart = () => {
    $api.cart.getCart().then((res) => {
      if (res.code === 200) {
        setCartList(res.data)
      }
    })
  }
  const showModal = () => {
    setIsModalVisible(true)
    getCart()
  }
  const handleCancel = () => {
    setIsModalVisible(false)
  }
  const onFoodCountChange = (count, index, index2) => {
    $api.cart
      .changeFoodCount({
        id: cartList[index]['foodList'][index2]['id'],
        count: count
      })
      .then((res) => {
        if (res.code === 200) {
          const tempList = [...cartList]
          tempList[index]['foodList'][index2].count = count
          setCartList(tempList)
        }
      })
  }
  const onSelectedChange = (index, index2) => {
    const tempList = [...cartList]
    if (!tempList[index]['foodList'][index2].isSelected) {
      tempList[index]['foodList'][index2].isSelected = true
    } else {
      tempList[index]['foodList'][index2].isSelected = false
    }

    setCartList(tempList)
  }
  const deleteFood = (index, index2) => {
    $api.cart
      .deleteFood({ id: cartList[index]['foodList'][index2].id })
      .then((res) => {
        if (res.code === 200) {
          const tempList = [...cartList]
          if (tempList[index]['foodList'].length === 1) {
            tempList.splice(index, 1)
          } else {
            tempList[index]['foodList'].splice(index2, 1)
          }
          setCartList(tempList)
        } else {
          message.error('delete error!')
        }
      })
  }
  const onCommentChange = (value, index) => {
    const tempList = [...cartList]
    tempList[index].comment = value
    setCartList(tempList)
  }
  const submitOrder = () => {
    const order = []
    cartList.forEach((item) => {
      let selectedList = []
      item.foodList.forEach((item2) => {
        if (item2.isSelected) {
          selectedList.push({ id: item2.id, count: item2.count })
        }
      })
      if (selectedList.length) {
        order.push({
          restaurant_id: item.information.id,
          food_list: selectedList,
          comment: item.comment
        })
      }
    })
    if (!order.length) {
      message.info('please select your food')
      return
    }
    if (!phoneNumber || !address) {
      message.info('please input your infomation')
      return
    }

    $api.cart
      .submitOrder({
        restaurant_list: order,
        address: address,
        phone_number: phoneNumber,
        latitude: 68.1,
        longitude: 33.5
      })
      .then((res) => {
        if (res.code === 200) {
          message.success('submit order sucessfully!')
          setIsModalVisible(false)
          let temp = [...cartList]
          for (let i = 0; i < temp.length; i++) {
            let item = temp[i]
            for (let j = 0; j < temp[i].foodList.length; j++) {
              let item2 = item.foodList[j]
              if (item2.isSelected) {
                item.foodList.splice(j, 1)
                j--
              }
            }
            if (!item.foodList.length) {
              temp.splice(i, 1)
            }
          }
          setCartList(temp)
        }
      })
  }
  let totalPrice = 0
  let totalCount = 0
  cartList.forEach((item) => {
    item.foodList.forEach((item2) => {
      if (item2.isSelected) {
        totalPrice += item2.count * item2.price * item2.discount
        totalCount += item2.count
      }
    })
  })
  const temp = cartList.map((item, index) => (
    <div key={index} className="mb-6">
      <div className="mb-2 text-xl">{item.information.name}</div>
      <Space direction="vertical" style={{ width: '100%' }}>
        {item.foodList.map((item2, index2) => (
          <div
            style={{ display: 'flex', justifyContent: 'space-between' }}
            key={index2}
            size="large"
          >
            <Checkbox
              onChange={() => onSelectedChange(index, index2)}
            ></Checkbox>
            <img src={item2.img} className="w-28 h-28"></img>
            <Space direction="vertical" size={4}>
              <div className="float-right mb-2 cursor-pointer">
                <CloseOutlined onClick={() => deleteFood(index, index2)} />
              </div>
              <Typography.Text
                style={{
                  width: 120
                }}
                ellipsis={{
                  tooltip: item2.name
                }}
              >
                <span className="text-base">{item2.name}</span>
              </Typography.Text>

              <Typography.Text
                style={{
                  width: 120
                }}
                ellipsis={{
                  tooltip: item2.description
                }}
              >
                {item2.description}
              </Typography.Text>
              <Space size="large">
                <span
                  className="pr-2 font-medium"
                  style={{ color: 'rgb(252, 85, 49)' }}
                >
                  ${(item2.price * item2.discount).toFixed(2)}
                  {item2.discount == 1 ? (
                    <div className="w-10 inline-block"></div>
                  ) : (
                    <>
                      &nbsp;&nbsp;
                      <span
                        style={{
                          color: 'rgb(160,160,160)',
                          textDecoration: 'line-through',
                          fontSize: '12px',
                          fontWeight: 300
                        }}
                      >
                        ${item2.price.toFixed(2)}
                      </span>
                    </>
                  )}
                </span>
                <InputNumber
                  style={{ width: '60px' }}
                  min={1}
                  max={99}
                  size="small"
                  value={item2.count}
                  onChange={(value) => onFoodCountChange(value, index, index2)}
                />
              </Space>
            </Space>
          </div>
        ))}
        <Input
          placeholder="your comment"
          value={item.comment}
          onChange={(e) => onCommentChange(e.target.value, index)}
        />
      </Space>
    </div>
  ))

  const foodList = !cartList || !cartList.length ? [] : temp
  return (
    <>
      <ShoppingCartOutlined onClick={showModal} className="text-3xl" />

      <Drawer
        title="My Cart"
        placement="right"
        onClose={handleCancel}
        visible={isModalVisible}
      >
        {foodList.length ? (
          <>
            {foodList}
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <Input
                placeholder="your phone number"
                value={phoneNumber}
                onChange={(e) => setPhoneNumber(e.target.value)}
              />
              <Input
                placeholder="your address"
                value={address}
                onChange={(e) => setAddress(e.target.value)}
              />
              <div className="text-xl ">
                {totalCount} pieces selected, in total:
                <span
                  className="pl-2 font-medium"
                  style={{ color: 'rgb(252, 85, 49)' }}
                >
                  ${totalPrice.toFixed(2)}
                </span>
              </div>
              <Button type="primary" block onClick={submitOrder}>
                submit order
              </Button>
            </Space>
          </>
        ) : (
          <Empty description={<span>no food in cart</span>} />
        )}
      </Drawer>
    </>
  )
}

export default Cart
